package com.example.blogback.utils;

import cn.hutool.system.UserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.apachecommons.CommonsLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * 生成和校验token的工具类
 */
@Data
@Component
@ConfigurationProperties(prefix = "jhl.jwt")
@Slf4j
public class JwtUtils {

    private String secret;
    private long expire;
    private String header;

    /**
     * 生成jwt token
     * @param userId
     * @return
     */
    public String generateToken(long userId){
//        当前时间
        Date nowDate = new Date();
//        过期时间，单位：ms
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);
        return Jwts.builder()
                .setHeaderParam("typ","Jwt")
                .setSubject(userId+"")
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
    }

//    验证token，解析
    public Claims getClaimByToken(String token){
        try{
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e){
            log.debug("validate is token error",e);
            return null;
        }
    }

//    token是否过期
    public boolean isTokenExpired(Date expiration){
        return expiration.before(new Date());
    }
}
